package com.zhilehuo.service.impl;

import com.github.houbb.pinyin.util.PinyinHelper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zhilehuo.common.BaseResponse;
import com.zhilehuo.mapper.ArticleMapper;
import com.zhilehuo.mapper.ParagraphMapper;
import com.zhilehuo.mapper.WordMapper;
import com.zhilehuo.model.DTO.ParagraphWithWords;
import com.zhilehuo.model.DTO.WordWithPinyin;
import com.zhilehuo.model.po.Article;
import com.zhilehuo.model.po.Paragraph;
import com.zhilehuo.model.po.Word;
import com.zhilehuo.model.vo.ArticleVo;
import com.zhilehuo.service.IArticleService;
import com.zhilehuo.util.ChineseUtil;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Lock;

@Service
@Slf4j
public class ArticleServiceImpl implements IArticleService {


    @Resource
    private ArticleMapper articleMapper;

    @Resource
    private ParagraphMapper paragraphMapper;

    @Resource
    private WordMapper wordMapper;



    @Override
    public PageInfo<ArticleVo> queryArticles(String title, String category, Integer pageNum, Integer pageSize) {
        // 开始分页
        PageHelper.startPage(pageNum, pageSize);

        List<ArticleVo> articleVos = articleMapper.selectArticles(title, category);
        return new PageInfo<>(articleVos);

    }

    @Override
//    @Transactional(rollbackFor = Exception.class)
    public BaseResponse<Boolean> insert(Article article) {

        try {

            Integer insert = articleMapper.insert(article);


            Article articleInsert = articleMapper.selectByTitleAndCategory(article);
            Integer articleId = articleInsert.getId();



            // 2. 自动分段
            List<Paragraph> paragraphs = segmentArticle(articleId, articleInsert.getContent());

            // 3. 批量插入段落
            if (!paragraphs.isEmpty()) {
                paragraphMapper.insertParagraphs(paragraphs);

                //插入过后需要重新查询
                List<Paragraph> paragraphInsert = paragraphMapper.selectByArticleId(articleId);

                // 4. 为每个段落处理拼音和字符
                List<Word> allWords = new ArrayList<>();
                for (Paragraph paragraph : paragraphInsert) {
                    List<Word> paragraphWords = extractWords(paragraph);
                    allWords.addAll(paragraphWords);
                }

                // 5. 批量插入拼音
                if (!allWords.isEmpty()) {
                    wordMapper.insertWords(allWords);
                }

            }
            return new BaseResponse<>(200, true,"插入成功");
        } catch (Exception e) {
            log.info("文章插入失败", e);
            throw new RuntimeException("事务失败，回滚", e); // 必须抛出 RuntimeException
        }


    }

    @Override
    public BaseResponse<List<ParagraphWithWords>> getArticleWithPinyin(Integer articleId) {
        // 获取文章内容
        Article article = articleMapper.selectById(articleId);
        if (article == null) {
            return new BaseResponse<>(401, null, "文章不存在");
        }

        // 获取文章对应的段落列表
        List<Paragraph> paragraphs = paragraphMapper.selectByArticleId(articleId);

        // 获取段落对应的拼音
        List<ParagraphWithWords> paragraphWithWordsList = new ArrayList<>();
        for (Paragraph paragraph : paragraphs) {
            // 获取每个段落的拼音信息
            List<Word> words = wordMapper.selectByParagraphId(paragraph.getId());
            List<WordWithPinyin> wordWithPinyinList = new ArrayList<>();
            for (Word word : words) {
                WordWithPinyin wordWithPinyin = new WordWithPinyin();
                wordWithPinyin.setIsPolyphonic(word.getIsPolyphonic());
                wordWithPinyin.setId(word.getId());
                wordWithPinyin.setCharacter(word.getCharacter());
                wordWithPinyin.setPinyin(word.getPinyin());
                wordWithPinyinList.add(wordWithPinyin);
            }
            ParagraphWithWords paragraphWithWords = new ParagraphWithWords();
            paragraphWithWords.setParagraph(paragraph);
            paragraphWithWords.setWords(wordWithPinyinList);
            paragraphWithWordsList.add(paragraphWithWords);
        }

        return new BaseResponse<>(200, paragraphWithWordsList);







    }


    /**
     * 提取每个段落的汉字及其拼音
     */
    private List<Word> extractWords(Paragraph paragraph) {
        List<Word> words = new ArrayList<>();
        String content = paragraph.getContent();

        for (int i = 0; i < content.length(); i++) {
            char ch = content.charAt(i);
            if (ChineseUtil.isChinese(ch)) {
                Word word = new Word();
                word.setParagraphId(paragraph.getId());
                word.setCharacter(String.valueOf(ch));
                word.setPinyin(PinyinHelper.toPinyin(String.valueOf(ch)));
                words.add(word);
            }
        }

        return words;
    }


    /**
     * 文章分段方法
     */
    private List<Paragraph> segmentArticle(Integer articleId, String content) {
        String[] paragraphContents = content.split("\n");
        List<Paragraph> paragraphs = new ArrayList<>();

        for (int i = 0; i < paragraphContents.length; i++) {
            if (StringUtils.hasText(paragraphContents[i])) {
                Paragraph paragraph = new Paragraph();
                paragraph.setArticleId(articleId);
                paragraph.setContent(paragraphContents[i]);
                paragraph.setParagraphOrder(i + 1);
                paragraphs.add(paragraph);
            }
        }

        return paragraphs;
    }
}
